package org.hfy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.hfy.common.ApiResponse;
import org.hfy.dto.LabelCreateDTO;
import org.hfy.service.LabelService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.io.UnsupportedEncodingException;

/**
 * 标签制作控制器
 * 
 * @author hfy
 * @version 1.0
 */
@RestController
@RequestMapping("/label")
public class LabelController {

    @Autowired
    private LabelService labelService;

    /**
     * 制作标签并下载PDF
     */
    @PostMapping("/create")
    public ResponseEntity<byte[]> createLabel(@Validated @RequestBody LabelCreateDTO labelData) {
        try {
            // 生成标签PDF
            byte[] pdfBytes = labelService.generateLabelPdf(labelData);
            
            // 生成文件名：Label_订单编号_时间戳.pdf (使用英文避免编码问题)
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileName = String.format("Label_%s_%s.pdf", 
                labelData.getOrderNumber().replaceAll("[^a-zA-Z0-9]", "_"), 
                timestamp);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            
            // 使用RFC 2047编码支持中文文件名
            try {
                String encodedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                headers.add("Content-Disposition", 
                    String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", 
                        fileName, encodedFileName));
            } catch (Exception encodeException) {
                // 编码失败时使用默认文件名
                headers.add("Content-Disposition", "attachment; filename=\"label.pdf\"");
            }
            
            headers.setContentLength(pdfBytes.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(pdfBytes);
                    
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 测试接口：验证标签数据
     */
    @PostMapping("/validate")
    public ApiResponse<String> validateLabel(@Validated @RequestBody LabelCreateDTO labelData) {
        return ApiResponse.success("标签数据验证通过");
    }
} 